import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { SystemUserDataItemType, SystemUserStateType } from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElSpace,
  ElButton,
  ElIcon,
  ElMessage,
  ElFormItem,
  ElInput,
  ElTag,
  ElMessageBox,
  ElLink
} from 'element-plus'
import {
  Plus,
  View,
  EditPen,
  Delete,
  User,
  Refresh
  // Upload,
  // Download
} from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import SystemUserOptionsModal from './options'
import UserRoleConfigurationModal from '../components/SystemUser/UserRoleConfigurationModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import ExportExcel from '~/components/ExportExcel'
import { handleTrim } from '~/utils/util'
import styles from '../index.module.scss'

export default defineComponent(function SystemUser() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const state = reactive<SystemUserStateType>({
    modalVisible: false,
    userRoleConfigVisible: false,
    exportVisible: false,
    type: 'read',
    record: {}
  })
  const formValues = reactive<SystemUserDataItemType>({})
  const userState = useVuexGetters('user', ['permission'])
  const systemUserState = useVuexGetters('systemUser', ['belongTenantEnum'])

  // 打开操作弹框
  const handleChangeOptionsModal = (
    type: SystemUserStateType['type'],
    record?: SystemUserDataItemType
  ) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) proSaasTableRef.value!?.toSearch()
  }

  // 切换用户角色配置弹框
  const handleChangeUserRoleConfigVisible = () => {
    // 打开弹框前逻辑
    if (!state.userRoleConfigVisible) {
      // 如果一个没勾选
      if (!proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '请选择至少一条数据' })
        return
      }
      // 如果勾选了但是tenantId不同
      const firstItem = proSaasTableRef.value!.selecteds[0]
      if (
        proSaasTableRef.value!.selecteds?.length > 1 &&
        !proSaasTableRef.value!.selecteds?.every((item) => item.tenantId === firstItem.tenantId)
      ) {
        ElMessage({ type: 'warning', message: '请选择所属租户相同的数据' })
        return
      }
      store.dispatch('systemRole/GetUserRoleSelectList', { tenantId: firstItem.tenantId })
    }
    state.userRoleConfigVisible = !state.userRoleConfigVisible
    if (!state.userRoleConfigVisible) proSaasTableRef.value!?.toSearch()
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: SystemUserDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item.id)?.join(',')
    ElMessageBox.confirm('确定将选择数据删除?', '确认提示', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemUser/DeleteSystemUserInfo', { ids: params }).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.clearSelection?.()
            proSaasTableRef.value!?.toSearch()
            ElMessage({ type: 'success', message: '操作成功' })
          }
        })
      })
      .catch(() => {})
  }

  // 重置勾选数据密码
  const handleResetUserPassword = () => {
    // 如果一个没勾选
    if (!proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    ElMessageBox.confirm('确定将选择账号密码重置为123456?', '重置密码', {
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemUser/ResetSystemUserPassword', {
          userIds: proSaasTableRef.value!.selecteds?.map?.((item) => item?.id)?.join(',')
        })
      })
      .catch(() => {})
  }

  // 切换导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const searchTable = () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  onMounted(() => {
    // 获取所属租户下拉列表
    store.dispatch('systemUser/GetBelongTenantSelectList')
  })

  const columns: TableColumnProps<SystemUserDataItemType>[] = [
    {
      label: '#',
      prop: 'tableIndex',
      width: 90,
      render: ({ $index }) => (
        <>
          {(proSaasTableRef.value!.pagination.currentPage - 1) *
            proSaasTableRef.value!.pagination.pageSize +
            $index +
            1}
        </>
      )
    },
    {
      label: '登录账号',
      prop: 'account',
      minWidth: 140
    },
    {
      label: '所属租户',
      prop: 'tenantId',
      minWidth: 220,
      enumValues: systemUserState.belongTenantEnum,
      showOverflowTooltip: true
    },

    /* {
      label: '用户昵称',
      prop: 'name',
      minWidth: 140,
      showOverflowTooltip: true
    }, */
    {
      label: '用户姓名',
      prop: 'realName',
      minWidth: 140,
      showOverflowTooltip: true
    },
    {
      label: '所属角色',
      prop: 'roleName',
      width: 180,
      render: ({ row }) => (
        <ElSpace direction="vertical" alignment="start">
          {row?.roleName &&
            row?.roleName
              ?.split(',')
              ?.map((item) => <ElTag class={styles['system-user-role-tag']}>{item}</ElTag>)}
        </ElSpace>
      )
    },
    {
      label: '所属部门',
      prop: 'deptName',
      width: 150,
      render: (_, value) => <ElTag class={styles['system-user-dept-tag']}>{value}</ElTag>
    },
    {
      label: '手机号码',
      prop: 'phone',
      minWidth: 200
    },
    {
      label: '操作',
      prop: 'options',
      width: 270,
      fixed: 'right',
      unFixed: true,
      align: 'center',
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('system_user_view') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
              <ElIcon>
                <View />
              </ElIcon>
              &nbsp; 查看
            </ElLink>
          )}
          {userState.permission.value.has('system_user_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('system_user_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]
  return () => (
    <ElCard>
      <ProSaasTable<SystemUserDataItemType>
        tableId="systemUser"
        ref={proSaasTableRef}
        columns={columns}
        // hasIndex
        hasSelection
        dispatchType="systemUser/GetSystemUserList"
        searchParams={{
          account: formValues.account && handleTrim(formValues.account),
          realName: formValues.realName && handleTrim(formValues.realName)
        }}
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="account" prop="account">
            <ElInput
              v-model={formValues.account}
              {...{ maxlength: 50 }}
              placeholder="登录账号"
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={searchTable}
              clearable
            />
          </ElFormItem>,
          <ElFormItem key="realName" prop="realName">
            <ElInput
              v-model={formValues.realName}
              {...{ maxlength: 50 }}
              placeholder="用户姓名"
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={searchTable}
              clearable
            />
          </ElFormItem>
        ]}
        headerTitle={
          <>
            {userState.permission.value.has('system_user_add') && (
              <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
            )}
            {userState.permission.value.has('system_user_remove') && (
              <ElButton type="danger" plain onClick={() => handleOpenDeleteConfirm()}>
                <ElIcon>
                  <Delete />
                </ElIcon>
                &nbsp; 删除
              </ElButton>
            )}
            {userState.permission.value.has('system_user_role') && (
              <ElButton type="info" plain onClick={handleChangeUserRoleConfigVisible}>
                <ElIcon>
                  <User />
                </ElIcon>
                &nbsp; 角色配置
              </ElButton>
            )}
            {userState.permission.value.has('system_user_reset') && (
              <ElButton type="primary" plain onClick={handleResetUserPassword}>
                <ElIcon>
                  <Refresh />
                </ElIcon>
                &nbsp; 密码重置
              </ElButton>
            )}
            {/* <ElButton type="success" plain>
              <ElIcon>
                <Upload />
              </ElIcon>
              &nbsp; 导入
            </ElButton> */}
            {/* <ElButton type="warning" plain onClick={handleChangeExportModal}>
              <ElIcon>
                <Download />
              </ElIcon>
              &nbsp; 导出
            </ElButton> */}
          </>
        }
      />
      {state.modalVisible && (
        <SystemUserOptionsModal
          visible={state.modalVisible}
          type={state.type}
          record={state.record}
          onCancel={() => handleChangeOptionsModal('read')}
        />
      )}
      {state.userRoleConfigVisible && (
        <UserRoleConfigurationModal
          visible={state.userRoleConfigVisible}
          users={proSaasTableRef.value!.selecteds}
          cancel={handleChangeUserRoleConfigVisible}
        />
      )}
      {state.exportVisible && (
        <ExportExcel
          visible={state.exportVisible}
          dispatchType="systemUser/ExportSystemUserList"
          columns={proSaasTableRef.value?.filterColumns}
          payload={{ params: formValues }}
          onCancel={handleChangeExportModal}
        />
      )}
    </ElCard>
  )
})
